using FluentValidation;
using Zhaoxi.Zhihu.Core.QuestionAggregate.Events;
using Zhaoxi.Zhihu.Core.QuestionAggregate.Specifications;
using Zhaoxi.Zhihu.SharedKerel.Messaging;
using Zhaoxi.Zhihu.SharedKerel.Result;
using Zhaoxi.Zhihu.UseCases.Common.Interface;

namespace Zhaoxi.Zhihu.UseCases.Answers.Command;

public record CreateAnswerLikeCommand(int AnswerId, bool IsLike) : ICommand<Result>;

public class CreateAnswerLikeCommandValidator : AbstractValidator<CreateAnswerLikeCommand>
{
    public CreateAnswerLikeCommandValidator()
    {
        RuleFor(command=> command. AnswerId).GreaterThan(0);
    }
}

public class CreateAnswerLikeCommandHandler(IAnswerRepositoy answers, IUser user)
    : ICommandHandler<CreateAnswerLikeCommand, Result>
{
    public async Task<Result> Handle(CreateAnswerLikeCommand request, CancellationToken cancellationToken)
    {
        var spec = new AnswerByIdWithLikeByUserIdSpec(request.AnswerId, user. Id !. Value);
        var answer = await answers.GetAnswerByIdWithLikeByUserIdAsync(spec, cancellationToken);
        if (answer == null) return Result.NotFound("回答不存在");
        var result = answer. AddLike(user.Id!.Value, request.IsLike);
        if (!result. IsSuccess) return result;
        answer.AddDomainEvent(new AnswerLikeEvent(answer.QuestionId));
        await answers.SaveChangesAsync(cancellationToken);
        return Result.Success();
    }
}